package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyCfg;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.*;
import com.lkd.exception.LogicException;
import com.lkd.feignService.UserService;
import com.lkd.feignService.VMService;
import com.lkd.http.viewModel.CancelTaskViewModel;
import com.lkd.http.viewModel.TaskViewModel;
import com.lkd.service.*;
import com.lkd.utils.DateDay;
import com.lkd.viewmodel.Pager;
import com.lkd.viewmodel.UserWork;
import com.lkd.viewmodel.VendingMachineViewModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private UserService userService;

    @Autowired
    private MqttProducer mqttProducer;

    @Autowired
    private TaskCollectService collectService;


    @Override
    @Transactional(rollbackFor = {Exception.class}, noRollbackFor = {LogicException.class})
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {
        checkCreateTask(taskViewModel.getInnerCode(), taskViewModel.getProductType());//验证
        if (hasTask(taskViewModel.getInnerCode(), taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }

        //向工单表插入一条记录
        TaskEntity taskEntity = new TaskEntity();

        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        BeanUtils.copyProperties(taskViewModel, taskEntity);
        taskEntity.setProductTypeId(taskViewModel.getProductType());
        String userName = userService.getUser(taskViewModel.getUserId()).getUserName();
        taskEntity.setUserName(userName);
        VendingMachineViewModel vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        taskEntity.setTaskCode(generateTaskCode());
        taskEntity.setAddr(vm.getNodeAddr());
        taskEntity.setRegionId(vm.getRegionId());

        taskEntity.setAssignorId(getLeastUser(vm.getRegionId(), true));

        this.save(taskEntity);

        //如果是补货工单，向工单明细表插入记录
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            taskViewModel.getDetails().forEach(d -> {
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(d, detailsEntity);
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }
        updateTaskZSet(taskEntity, 1);

        return true;

    }

    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); //日期字符串
        String key = "lkd.task.code." + date;//redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }


    @Override
    public boolean completeTask(long id) {
        return completeTask(id, 0d, 0d, "");

    }

    /**
     * 完成工单
     *
     * @param
     * @param lat
     * @param lon
     * @param addr
     * @return
     */
    @Override
    public boolean completeTask(Long id, Double lat, Double lon, String addr) {
        TaskEntity taskEntity = this.getById(id);
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("工单已经结束");

        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        taskEntity.setAddr(addr);//添加地址
        this.updateById(taskEntity);
        //如果是投放工单或撤机工单
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_DEPLOY || taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_REVOKE) {
            noticeVMServiceStatus(taskEntity, lat, lon);
        }
        //如果是补货工单
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            noticeVMServiceSupply(taskEntity);
        }
        return true;
    }

    /**
     * 运维工单封装与下发
     *
     * @param taskEntity
     */
    private void noticeVMServiceStatus(TaskEntity taskEntity, Double lat, Double lon) {
        //向消息队列发送消息，通知售货机更改状态
        //封装协议
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode()); //售货机编号
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());//工单类型
        taskCompleteContract.setLat(lat); //纬度
        taskCompleteContract.setLon(lon);//经度
        //发送到emq
        try {
            mqttProducer.send(TopicConfig.COMPLETED_TASK_TOPIC, 2, taskCompleteContract);
        } catch (Exception e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }

    }

    /**
     * @return
     */
    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId, VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }

    /**
     * 接受工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean accept(Long id) {
        TaskEntity task = this.getById(id); //查询工单
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE) {
            throw new LogicException("工单状态不是待处理");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS); //修改工单状态为进行
        return this.updateById(task);
    }


    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVm) {
        TaskEntity task = this.getById(id);
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("该工单已经结束");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(cancelVm.getDesc());
        updateTaskZSet(task, -1);
        return this.updateById(task);
    }


    /**
     * 补货协议封装与下发
     *
     * @param taskEntity
     */
    private void noticeVMServiceSupply(TaskEntity taskEntity) {

        QueryWrapper<TaskDetailsEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(TaskDetailsEntity::getTaskId, taskEntity.getTaskId());
        List<TaskDetailsEntity> details = taskDetailsService.list(qw);
        SupplyCfg supplyCfg = new SupplyCfg();
        supplyCfg.setInnerCode(taskEntity.getInnerCode());
        List<SupplyChannel> supplyChannels = Lists.newArrayList();
        details.forEach(d -> {
            SupplyChannel channel = new SupplyChannel();
            channel.setChannelId(d.getChannelCode());
            channel.setCapacity(d.getExpectCapacity());
            supplyChannels.add(channel);
        });
        supplyCfg.setSupplyData(supplyChannels);

        //下发补货协议
        //发送到emq
        try {
            mqttProducer.send(TopicConfig.COMPLETED_TASK_TOPIC, 2, supplyCfg);
        } catch (Exception e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }

    }

    /**
     * 同一台设备下是否存在未完成的工单
     *
     * @param innerCode
     * @param productionType
     * @return
     */
    private boolean hasTask(String innerCode, int productionType) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productionType)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);

        return this.count(qw) > 0;
    }

    private void checkCreateTask(String innerCode, int productType) throws LogicException {
        VendingMachineViewModel vmInfo = vmService.getVMInfo(innerCode);//根据设备编号查询设备
        if (vmInfo == null) throw new LogicException("设备校验失败");
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备已在运营");
        }

        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }

        if (productType == VMSystem.TASK_TYPE_REVOKE && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }
    }

    /**
     * 更新工单列表
     *
     * @param taskEntity
     * @param score
     */
    private void updateTaskZSet(TaskEntity taskEntity, int score) {
        String roleCode = "1003"; //运维员
        if (taskEntity.getProductTypeId().intValue() == 2) { //如果是补货工单
            roleCode = "1002"; //运营员
        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + taskEntity.getRegionId() + "." + roleCode;
        redisTemplate.opsForZSet().incrementScore(key, taskEntity.getAssignorId(), score);
    }


    @Override
    public Integer getLeastUser(Long regionId, Boolean isRepair) {
        String roleCode = "1002";
        if (isRepair) { //如果是维修工单
            roleCode = "1003";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + regionId + "." + roleCode;
        Set<Object> range = redisTemplate.opsForZSet().range(key, 0, 1);
        if (range == null || range.isEmpty()) {
            throw new LogicException("该区域暂时没有相关工作人员");
        }
        return (Integer) new ArrayList<>(range).get(0);
    }

    public static void main(String[] args) {
        LocalDate startTime = LocalDate.parse("2021-05-03", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endTime = LocalDate.parse("2021-06-03", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        System.out.println(endTime.toEpochDay() - startTime.toEpochDay());
        System.out.println(startTime.plusDays(1));
//        startTime.
    }
    /**
     * 工单状态统计
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<TaskCollectEntity> collectReport(String start, String end) {
        ArrayList<TaskCollectEntity> list = new ArrayList<>();
        List<LocalDate> dateList = DateDay.getDateDay(start, end);
        TaskCollectEntity entity = null;
        for (LocalDate localDate : dateList) {
            List<TaskCollectEntity> entityList = collectService.list(Wrappers.<TaskCollectEntity>lambdaQuery()
                    .eq(TaskCollectEntity::getCollectDate, localDate)
                    .orderByDesc(TaskCollectEntity::getCollectDate));
            //.le(TaskCollectEntity::getCollectDate, end));
            for (TaskCollectEntity collectEntity : entityList) {
                entity = new TaskCollectEntity();
                BeanUtils.copyProperties(collectEntity,entity);
                list.add(entity);
            }
        }
        //collectService.save(entity);
        return list;

    }
    @Autowired
    private TaskTypeService taskTypeService;
    @Override
    public List top10(String start, String end, Boolean isRepair, String regionId) {
        LambdaQueryWrapper<TaskEntity> queryWrapper = Wrappers.<TaskEntity>lambdaQuery();
        List<Integer> collect=null;
        if (isRepair){
            List<TaskTypeEntity> list = taskTypeService.list(Wrappers.<TaskTypeEntity>lambdaQuery().eq(TaskTypeEntity::getType, 1));
            collect = list.stream().map(s -> {
                return s.getTypeId();
            }).collect(Collectors.toList());
        }else {
            List<TaskTypeEntity> list = taskTypeService.list(Wrappers.<TaskTypeEntity>lambdaQuery().eq(TaskTypeEntity::getType, 2));
            collect = list.stream().map(s -> {
                return s.getTypeId();
            }).collect(Collectors.toList());
        }
        if (Long.valueOf(regionId)!=0) {
            queryWrapper.in(TaskEntity::getProductTypeId, collect).le(AbstractEntity::getCreateTime, end)
                    .ge(AbstractEntity::getCreateTime, start).eq(TaskEntity::getRegionId,regionId);
        }else {
            queryWrapper.in(TaskEntity::getProductTypeId, collect).le(AbstractEntity::getCreateTime, end)
                    .ge(AbstractEntity::getCreateTime, start);
        }
        List<TaskEntity> list = list(queryWrapper);
        Map<String, List<TaskEntity>> collect1 = list.stream().collect(Collectors.groupingBy(TaskEntity::getUserName));
        ArrayList<Map> mapArrayList = new ArrayList<>();
        collect1.entrySet().forEach(e->{
            TreeMap<String, Object> map = new TreeMap<>();
            map.put("userName",e.getKey());
            map.put("workCount",e.getValue().size());
            mapArrayList.add(map);
        });

        Collections.sort(mapArrayList, new Comparator<Map>() {
            @Override
            public int compare(Map o1, Map o2) {
               return (Integer)o2.get("workCount")-(Integer)o1.get("workCount");
            }
        });
        List<Map> collect2 = mapArrayList.stream().limit(10).collect(Collectors.toList());
        return collect2;
    }




    //获取工单的统计情况
    @Override
    public List<TaskReportInfo> getTaskReportInfo(LocalDateTime start, LocalDateTime end) {
        //运营工单总数total
        var supplyTotalFuture = CompletableFuture.supplyAsync(() -> this.taskCount(start, end, false, null));
        //运维工单总数
        var repairTotalFuture = CompletableFuture.supplyAsync(()->this.taskCount( start,end,true, null ));
        //完成的运营工单总数
        var completedSupplyFuture = CompletableFuture.supplyAsync(()->this.taskCount( start,end,false, VMSystem.TASK_STATUS_FINISH ));
        //完成的运维工单总数
        var completedRepairFuture = CompletableFuture.supplyAsync(()-> this.taskCount( start,end,true, VMSystem.TASK_STATUS_FINISH ));
        //拒绝掉的运营工单总数
        var cancelSupplyFuture = CompletableFuture.supplyAsync(()->this.taskCount( start,end,false, VMSystem.TASK_STATUS_CANCEL ));
        //拒绝掉的运维工单总数
        var cancelRepairFuture = CompletableFuture.supplyAsync(()->this.taskCount( start,end,true, VMSystem.TASK_STATUS_CANCEL ));
        // 获取运营人员数量
        var operatorCountFuture = CompletableFuture.supplyAsync(()-> userService.getOperatorCount());
        //获取运维人员总数
        var repairerCountFuture = CompletableFuture.supplyAsync(()-> userService.getRepairerCount());

        //并行处理
        CompletableFuture.allOf(supplyTotalFuture,
                repairTotalFuture,
                cancelSupplyFuture,
                cancelRepairFuture,
                completedSupplyFuture,
                completedRepairFuture,
                operatorCountFuture,
                repairerCountFuture
        ).join();

        List<TaskReportInfo> result = Lists.newArrayList();
        var supplyTaskInfo = new TaskReportInfo();
        var repairTaskInfo = new TaskReportInfo();

        try {
            supplyTaskInfo.setTotal(supplyTotalFuture.get());
            supplyTaskInfo.setCancelTotal(cancelSupplyFuture.get());
            supplyTaskInfo.setCompletedTotal(completedSupplyFuture.get());
            supplyTaskInfo.setRepair(false);
            supplyTaskInfo.setWorkerCount(operatorCountFuture.get());
            result.add(supplyTaskInfo);

            repairTaskInfo.setTotal(repairTotalFuture.get());
            repairTaskInfo.setCancelTotal(cancelRepairFuture.get());
            repairTaskInfo.setCompletedTotal(completedRepairFuture.get());
            repairTaskInfo.setRepair(true);
            repairTaskInfo.setWorkerCount(repairerCountFuture.get());
            result.add(repairTaskInfo);


        } catch (Exception e) {
            log.error("构建工单统计数据失败",e);
        }
        return result;
    }

    //根据工单状态获取用户当月工单数
    private Integer getCountByUserId(Integer userId, Integer taskStatus, LocalDate start, LocalDateTime end){
        var qw = new LambdaQueryWrapper<TaskEntity>();
        qw.ge(TaskEntity::getUpdateTime,start)
                .le(TaskEntity::getUpdateTime,end);
        if (taskStatus!=null){
            qw.eq(TaskEntity::getTaskStatus,taskStatus);
        }
        if (userId!=null){
            qw.eq(TaskEntity::getUserId,userId);
        }
        return this.count(qw);
    }

    //获取用户工作量详情
    @Override
    public UserWork getUserWork(Integer userId, LocalDateTime start, LocalDateTime end) {
        var userWork = new UserWork();
        userWork.setUserId(userId);
        //并行处理提高程序吞吐量  获取用户完成工单数
        var workCountFuture =CompletableFuture.supplyAsync(()-> this.getCountByUserId(userId,VMSystem.TASK_STATUS_CANCEL,start.toLocalDate(),end))
                .whenComplete((r,e)->{
                    if (e!=null){
                        userWork.setWorkCount(0);
                        log.error("user work error",e);
                    }else {
                        userWork.setWorkCount(r);
                    }
                });
        //获取工单总数
        var totalFuture =CompletableFuture.supplyAsync(()-> this.getCountByUserId(userId, null,start.toLocalDate(),end))
                .whenComplete((r,e)->{
                    if (e!=null){
                        userWork.setWorkCount(0);
                        log.error("user work error",e);
                    }else {
                        userWork.setTotal(r);
                    }
                });

        //获取用户拒绝工单数
        var cancelCountFuture = CompletableFuture
                .supplyAsync(()-> this.getCountByUserId(userId,VMSystem.TASK_STATUS_CANCEL,start.toLocalDate(),end))
                .whenComplete((r,e)->{
                    if (e!=null){
                        userWork.setCancelCount(0);
                        log.error("user work error",e);
                    }else {
                        userWork.setCancelCount(r);
                    }
        });

        //获取进行中的工单数
        var progressTotalFuture =CompletableFuture.supplyAsync(()->
                this.getCountByUserId(userId,VMSystem.TASK_STATUS_PROGRESS,start.toLocalDate(),end))
                .whenComplete((r,e)->{
                    if (e!=null){
                        userWork.setProgressTotal(0);
                        log.error("user work error",e);
                    }else {
                        userWork.setProgressTotal(r);
                    }
        });
    CompletableFuture.allOf(workCountFuture,cancelCountFuture,progressTotalFuture).join();
        return userWork;
    }

    /**
     * 统计工单数量
     * @param start
     * @param end
     * @param repair 是否是运维工单
     * @param taskStatus
     * @return
     */
    private int taskCount( LocalDateTime start, LocalDateTime end ,Boolean repair ,Integer taskStatus ){
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        qw.ge(TaskEntity::getUpdateTime,start)
                .le(TaskEntity::getUpdateTime,end);
        //按工单状态查询
        if(taskStatus!=null){
            qw.eq(TaskEntity::getTaskStatus,taskStatus);
        }
        if(repair){//如果是运维工单
            qw.ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }else{
            qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }
        return this.count(qw);
    }
}
